const parentNode = document.querySelector('.main_bg') // 顶级节点
const scoreNode = document.querySelector('.score') // 得分节点
const beatNode = document.querySelector('.beat') // 飞机节点
const gameOverNode = document.querySelector('.game_over') // 游戏结束节点
const overScoreNode = document.querySelector('.over_score') // 游戏结束得分节点
const overBeatNode = document.querySelector('.over_beat') // 游戏结束飞机节点
const exitNode = document.querySelector('.exit') // 退出节点
const restartNode = document.querySelector('.restart') // 重新开始节点

let createEnemyPlaneInterval = null // 创建敌机的定时器
let createEnemyPlaneInterval2 = null // 创建中型敌机的定时器
let createEnemyPlaneInterval3 = null // 创建大型敌机的定时器
let enemyMoveInterval = null // 敌机移动的定时器
let bulletCreateInterval = null // 创建子弹的定时器
let movePlaneInterval = null // 主角机移动的定时器
let moveBulletInterval = null // 子弹移动的定时器
let gameOverInterval = null // 游戏结束的定时器
let createSubInterval = null // 创建陨石的定时器

const bullets = [] // 子弹数组
const enemyPlaneList = [] // 敌机数组
const subList = [] // 陨石数组

const shotAudio = document.querySelector('.arrow_shot') // 射击音效
const bombAudio = document.querySelector('.bomb') // 爆炸音效

gameOverNode.style.visibility = 'hidden' // 游戏结束节点隐藏

// 陨石类
class subClass {
  constructor() {
    this.node = document.createElement('img')
    this.node.style.position = 'absolute'
    this.node.src = './images/BgSub_陨石.png'
    this.node.className = 'sub'
    parentNode.appendChild(this.node)
    this.x = Math.floor(Math.random() * (parentNode.offsetWidth - 66) + 66)
    this.y = 0
    this.node.style.left = this.x + 'px'
    this.node.style.top = this.y + 'px'
  }
  // 陨石移动
  move() {
    this.y += 2
    this.node.style.top = this.y + 'px'
  }
}

// 创建陨石
createSubInterval = setInterval(function () {
  const sub = new subClass()
  subList.push(sub)
}, 1000)

// 陨石移动
subMoveInterval = setInterval(function () {
  subList.forEach((item) => {
    item.move()
    planeHitStone()
    if (item.y > parentNode.offsetHeight) {
      parentNode.removeChild(item.node)
      subList.splice(subList.indexOf(item), 1)
    }
  })
})

// 敌机类
class enemyPlaneClass {
  constructor() {
    this.node = document.createElement('img')
    this.node.style.position = 'absolute'
    this.node.src = './images/enemy1_fly_1.png'
    parentNode.appendChild(this.node)
    this.x = Math.floor(Math.random() * (parentNode.offsetWidth - 66) + 66)
    this.y = 0
    this.node.style.left = this.x + 'px'
    this.node.style.top = this.y + 'px'
    this.isDay = false // 是否被击中
    this.hiddleTime = 50 // 击中后隐藏时间
    this.type = 1 // 敌机类型
  }
  // 敌机移动
  move() {
    this.y += 2
    this.node.style.top = this.y + 'px'
  }
}

createEnemyPlaneInterval = setInterval(function () {
  const enemyPlane = new enemyPlaneClass()
  enemyPlaneList.push(enemyPlane)
}, 1000)

// 敌机移动
enemyMoveInterval = setInterval(function () {
  enemyPlaneList.forEach((item) => {
    if (!item.isDay) {
      item.move()
      if (item.y > parentNode.offsetHeight) {
        parentNode.removeChild(item.node)
        enemyPlaneList.splice(enemyPlaneList.indexOf(item), 1)
      }
    } else {
      item.hiddleTime -= 20
      if (item.hiddleTime <= 0) {
        parentNode.removeChild(item.node)
        enemyPlaneList.splice(enemyPlaneList.indexOf(item), 1)
      }
    }
  })
}, 30)

// 中型敌机类
class enemyPlaneClass2 {
  constructor() {
    this.node = document.createElement('img')
    this.node.style.position = 'absolute'
    this.node.src = './images/中飞机.png'
    parentNode.appendChild(this.node)
    this.x = Math.floor(Math.random() * (parentNode.offsetWidth - 66) + 66)
    this.y = 0
    this.node.style.left = this.x + 'px'
    this.node.style.top = this.y + 'px'
    this.bulletNum = 0 // 被子弹击中的数量
    this.isDay = false // 是否被击中
    this.hiddleTime = 50 // 击中后隐藏时间
    this.type = 2 // 敌机类型
  }
  // 敌机移动
  move() {
    this.y += 4
    this.node.style.top = this.y + 'px'
  }
}

// 创建中型敌机
function createEnemyPlane2(duration = 1000) {
  setInterval(function () {
    const enemyPlane = new enemyPlaneClass2()
    enemyPlaneList.push(enemyPlane)
  }, duration)
}
// 当得分大于30的时候出现中型敌机
createEnemyPlaneInterval2 = setInterval(function () {
  let s = beatNode.innerText.split(':')[1]
  if (s > 1) {
    console.log('中型敌机')
    const time = Math.floor(Math.random() * 5000 + 8000)
    createEnemyPlane2(time)
  }
}, 15000)

// 大型敌机类
class enemyPlaneClass3 {
  constructor() {
    this.node = document.createElement('img')
    this.node.style.position = 'absolute'
    this.node.src = './images/大飞机.png'
    this.node.className = 'big_plane'
    parentNode.appendChild(this.node)
    this.x = Math.floor(Math.random() * (300 - 100 + 1)) + 100
    this.y = 0
    this.node.style.left = this.x + 'px'
    this.node.style.top = this.y + 'px'
    this.bulletNum = 0 // 被子弹击中的数量
    this.isDay = false // 是否被击中
    this.hiddleTime = 50 // 击中后隐藏时间
    this.type = 3 // 敌机类型
  }
  // 敌机移动
  move() {
    // 曲线移动
    this.y += 0.5
    this.node.style.top = this.y + 'px'
    this.x += 0.5
    this.node.style.left = this.x + 'px'
  }
}
// 创建大型敌机
function createEnemyPlane3(duration = 1000) {
  setInterval(function () {
    const enemyPlane = new enemyPlaneClass3()
    enemyPlaneList.push(enemyPlane)
  }, duration)
}
// 当得分大于50的时候出现大型敌机
createEnemyPlaneInterval3 = setInterval(function () {
  let s = beatNode.innerText.split(':')[1]
  if (s > 1) {
    console.log('大型敌机')
    const time = Math.floor(Math.random() * 5000 + 8000)
    createEnemyPlane3(time)
  }
}, 15000)

// 主角机类
class planeClass {
  constructor(imageUrl, x, y, speed = 5) {
    this.node = document.createElement('img')
    this.node.style.position = 'absolute'
    this.node.src = imageUrl
    this.x = x
    this.y = y
    this.speed = speed
    this.node.style.left = x + 'px'
    this.node.style.top = y + 'px'
    this.isDay = false // 是否死亡
    this.hiddleTime = 50 // 击中后隐藏时间
    parentNode.appendChild(this.node)
  }
  // 上
  moveUp = function () {
    this.y -= this.speed
    this.node.style.top = this.y + 'px'
    // 边界判断
    if (this.y < 0) {
      this.y = 0
    }
  }
  // 下
  moveDown = function () {
    this.y += this.speed
    this.node.style.top = this.y + 'px'
    // 边界判断
    if (this.y > parentNode.offsetHeight - 80) {
      this.y = parentNode.offsetHeight - 80
    }
  }
  // 左
  moveLeft = function () {
    this.x -= this.speed
    this.node.style.left = this.x + 'px'
    // 边界判断
    if (this.x < -66) {
      this.x = parentNode.offsetWidth - 66
    }
  }
  // 右
  moveRight = function () {
    this.x += this.speed
    this.node.style.left = this.x + 'px'
    // 边界判断
    if (this.x > parentNode.offsetWidth) {
      this.x = 0
    }
  }
}

// 创建主角机
let leftBtn = false
let rightBtn = false
let upBtn = false
let downBtn = false
const plane = new planeClass('./images/myplane.gif', 165, 500, 1)

// 移动主角机
document.addEventListener('keydown', function (e) {
  switch (e.key) {
    case 'ArrowLeft':
      leftBtn = true
      break
    case 'ArrowUp':
      upBtn = true
      break
    case 'ArrowRight':
      rightBtn = true
      break
    case 'ArrowDown':
      downBtn = true
      break
  }
})

// 键盘松开
document.addEventListener('keyup', function (e) {
  switch (e.key) {
    case 'ArrowLeft':
      leftBtn = false
      break
    case 'ArrowUp':
      upBtn = false
      break
    case 'ArrowRight':
      rightBtn = false
      break
    case 'ArrowDown':
      downBtn = false
      break
  }
})

// 主角机移动
movePlaneInterval = setInterval(function () {
  if (leftBtn) {
    plane.moveLeft()
  }
  if (rightBtn) {
    plane.moveRight()
  }
  if (upBtn) {
    plane.moveUp()
  }
  if (downBtn) {
    plane.moveDown()
  }
  // 主角机和敌机发生碰撞
  planeHitEnemy()
})

// 子弹类
class bulletClass {
  constructor(imageUrl, x, y, speed = 5) {
    this.x = x
    this.y = y
    this.speed = speed
    this.node = document.createElement('img')
    this.node.src = imageUrl
    this.node.style.position = 'absolute'
    this.node.style.left = x + 'px'
    this.node.style.top = y + 'px'
  }
  // 移动
  move() {
    this.y -= this.speed
    this.node.style.top = parseInt(this.node.style.top) - this.speed + 'px'
  }
}

// 创建子弹
function createBullet() {
  const bullet = new bulletClass(
    './images/bullet1.png',
    plane.x + 31,
    plane.y - 10
  )
  parentNode.appendChild(bullet.node)
  bullets.push(bullet)
  shotAudio.play()
  return bullet
}
bulletCreateInterval = setInterval(() => {
  createBullet()
}, 500)

// 移动子弹
moveBulletInterval = setInterval(() => {
  for (let i = 0; i < bullets.length; i++) {
    bullets[i].move()
    // 边界判断
    if (bullets[i].y < 0) {
      parentNode.removeChild(bullets[i].node)
      bullets.splice(i, 1)
    }
    // 子弹和敌机发生碰撞
    bulletHitEnemy()
  }
})

// 子弹和敌机发生碰撞
function bulletHitEnemy() {
  for (let i = 0; i < bullets.length; i++) {
    for (let j = 0; j < enemyPlaneList.length; j++) {
      if (
        bullets[i]?.x >= enemyPlaneList[j]?.x &&
        bullets[i].x <= enemyPlaneList[j].x + 34 &&
        bullets[i].y >= enemyPlaneList[j].y &&
        bullets[i].y <= enemyPlaneList[j].y + 24
      ) {
        // 判断敌机类型
        if (enemyPlaneList[j].type === 1) {
          // 普通敌机
          parentNode.removeChild(bullets[i].node)
          bullets.splice(i, 1)
          enemyPlaneList[j].node.src = './images/小飞机爆炸.gif'
          enemyPlaneList[j].isDay = true
          bombAudio.play()
          // 增加分数和击败
          scoreNode.innerText = `得分:${
            Number(scoreNode.innerText.split(':')[1]) + 2
          }`
          beatNode.innerText = `击败:${
            Number(beatNode.innerText.split(':')[1]) + 1
          }`
        } else if (enemyPlaneList[j].type === 2) {
          // 中型敌机
          parentNode.removeChild(bullets[i].node)
          bullets.splice(i, 1)
          enemyPlaneList[j].bulletNum += 1
          console.log(enemyPlaneList[j].bulletNum)
          if (enemyPlaneList[j].bulletNum === 2) {
            enemyPlaneList[j].node.src = './images/中飞机爆炸.gif'
            enemyPlaneList[j].isDay = true
            bombAudio.play()
            // 增加分数和击败
            scoreNode.innerText = `得分:${
              Number(scoreNode.innerText.split(':')[1]) + 5
            }`
            beatNode.innerText = `击败:${
              Number(beatNode.innerText.split(':')[1]) + 1
            }`
          }
        } else if (enemyPlaneList[j].type === 3) {
          parentNode.removeChild(bullets[i].node)
          bullets.splice(i, 1)
          enemyPlaneList[j].bulletNum += 1
          if (enemyPlaneList[j].bulletNum === 5) {
            enemyPlaneList[j].node.src = './images/大飞机爆炸.gif'
            enemyPlaneList[j].isDay = true
            bombAudio.play()
            // 增加分数和击败
            scoreNode.innerText = `得分:${
              Number(scoreNode.innerText.split(':')[1]) + 10
            }`
            beatNode.innerText = `击败:${
              Number(beatNode.innerText.split(':')[1]) + 1
            }`
          }
        }
      }
    }
  }
}

// 主角机和敌机发生碰撞
function planeHitEnemy() {
  for (let i = 0; i < enemyPlaneList.length; i++) {
    if (
      enemyPlaneList[i].x >= plane.x &&
      enemyPlaneList[i].x <= plane.x + 66 &&
      enemyPlaneList[i].y >= plane.y &&
      enemyPlaneList[i].y <= plane.y + 66
    ) {
      enemyPlaneList[i].isDay = true
      enemyPlaneList[i].node.src = './images/小飞机爆炸.gif'
      plane.node.src = './images/本方飞机爆炸.gif'
      plane.isDay = true
      gameOver()
    }
  }
}

// 主角机和陨石发送碰撞
function planeHitStone() {
  for (let i = 0; i < subList.length; i++) {
    if (
      subList[i].x >= plane.x &&
      subList[i].x <= plane.x + 66 &&
      subList[i].y >= plane.y &&
      subList[i].y <= plane.y + 66
    ) {
      plane.node.src = './images/本方飞机爆炸.gif'
      plane.isDay = true
      gameOver()
    }
  }
}

// 游戏结束
const gameOver = () => {
  clearInterval(createEnemyPlaneInterval)
  clearInterval(bulletCreateInterval)
  clearInterval(moveBulletInterval)
  clearInterval(movePlaneInterval)
  clearInterval(enemyMoveInterval)
  clearInterval(createEnemyPlaneInterval2)
  clearInterval(createSubInterval)
  setTimeout(() => {
    plane.node.remove()
    gameOverNode.style.visibility = 'visible'
    overBeatNode.innerHTML = `击败:${beatNode.innerText.split(':')[1]}`
    overScoreNode.innerHTML = `得分:${scoreNode.innerText.split(':')[1]}`
  }, 200)
  for (let i = 0; i < enemyPlaneList.length; i++) {
    enemyPlaneList[i].node.remove()
  }
  bombAudio.play()
}

// 点击退出游戏
exitNode.addEventListener('click', (e) => {
  window.close()
})

// 点击重新开始游戏
restartNode.addEventListener('click', (e) => {
  window.location.reload()
})
